/*
 * Copyright (c) 2008-2011, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.flickr;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.locks.ReentrantLock;

import javax.swing.AbstractAction;

import javax.swing.ImageIcon;
import org.panteleyev.blogapi.IBlogEntry;
import org.panteleyev.blogclient.BlogPostEditorFrame;
import org.panteleyev.blogclient.BloggerFrame;
import org.panteleyev.blogclient.IPhotoUserProfile;
import org.panteleyev.blogclient.MainClass;
import org.panteleyev.blogclient.ProfileDialog;
import org.panteleyev.blogclient.UserProfile;
import org.panteleyev.blogclient.UserProfileType;
import org.panteleyev.flickrapi.AuthResult;
import org.panteleyev.flickrapi.FlickrAccount;
import org.panteleyev.flickrapi.FlickrException;
import org.panteleyev.flickrapi.FlickrPhoto;
import org.panteleyev.flickrapi.FlickrPhotoInfo;
import org.panteleyev.flickrapi.FlickrPhotoSet;
import org.panteleyev.flickrapi.SizeTable;

import com.google.common.collect.ImmutableList;
import org.panteleyev.blogclient.Icon;
import org.panteleyev.flickrapi.FlickrBlogEntry;

public class FLUserProfile extends UserProfile<FlickrBlogEntry> implements IPhotoUserProfile, Serializable {
    private final static long serialVersionUID = 20100206L;

    /* File names */
    private static final String SETS_FILE           = "photosets.pb";
    private static final String PHOTO_INFO_FILE     = "photoinfo.pb";
    private static final String PHOTO_SIZES_FILE    = "photosizes.pb";

    /* Serializable fields */
    private String token = "";
    private String nsid = "";

    /* Transient fields */
    private transient FlickrAccount                     account;
    private transient HashMap<String,FlickrPhotoInfo>   photoInfo;
    private transient HashMap<String,SizeTable>         photoSizes;
    private transient ReentrantLock                     photoInfoLock;
    private transient ReentrantLock                     photoSizesLock;

    public FLUserProfile(String name, String server) {
        super(UserProfileType.FLICKR, name, server);
        createTransientObjects();
    }

    private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException {
        stream.defaultReadObject();
        createTransientObjects();
    }

    private void createTransientObjects() {
        photoInfo = new HashMap<>();
        photoSizes = new HashMap<>();
        photoInfoLock = new ReentrantLock();
        photoSizesLock = new ReentrantLock();
    }

    public String getToken() {
        return token;
    }

    public FlickrAccount getAccount() {
        return account;
    }

    public void setAuthResult(AuthResult result) {
        token = result.getToken();
        nsid = result.getUserNSID();
    }

    void setAccount(FlickrAccount account) {
        this.account = account;
    }

    @Override
    public ProfileDialog createProfileDialog(BloggerFrame frame) {
        return null;
    }

    @Override
    public ArrayList<AbstractAction> getProfileActions() {
        return null;
    }

    @Override
    public String getProfileMenuName() {
        return "Flickr";
    }

    @Override
    public ArrayList<AbstractAction> getProfileToolBarActions() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean getStorePasswd() {
        return true;
    }

    @Override
    public boolean login(boolean store, boolean offl) {
        account = new FlickrAccount(token, nsid);
        setOnline(true);

        try {
            if (Thread.interrupted()) {
                return false;
            }

            account.loadUserPhotosUrl();
            if (Thread.interrupted()) {
                return false;
            }

            restorePhotoInfo();
            restorePhotoSizes();
            if (Thread.interrupted()) {
                return false;
            }

            setAccount(account);
            setConnected(true);

            return true;
        } catch (IOException | FlickrException e) {
            MainClass.handleException(null, e);
            return false;
        }
    }

    @Override
    public void postLoginUIActions() {
    }

    @Override
    public void onNewPost() {
    }

    @Override
    public void openStartupWindow() {
        new PhotoSetListFrame(this).setVisible(true);
    }

    @Override
    public void onHistoryFrameAction() {
    }

    @Override
    public String getImageCacheName() {
        return "flickr";
    }

    public void storePhotoSets(ImmutableList<FlickrPhotoSet> photoSets) {
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDirectory(), SETS_FILE)))) {
            out.writeInt(photoSets.size());
            for (FlickrPhotoSet set : photoSets) {
                out.writeObject(set);
            }
        } catch (Exception ex) {
            MainClass.handleException(null, ex);
        }
    }

    public ImmutableList<FlickrPhotoSet> restorePhotoSets() {
        ArrayList<FlickrPhotoSet> temp = new ArrayList<>();

        File file = new File(getCacheDirectory(), SETS_FILE);
        if (file.exists()) {
            try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
                int size = in.readInt();
                temp.ensureCapacity(size);
                for (int i = 0; i < size; ++i) {
                    temp.add((FlickrPhotoSet)in.readObject());
                }
            } catch (IOException | ClassNotFoundException ex) {
                MainClass.handleException(null, ex);
            }
        }

        return ImmutableList.copyOf(temp);
    }

    void addPhotoInfo(FlickrPhotoInfo info) {
        try {
            photoInfoLock.lock();
            photoInfo.put(info.getId(), info);
        } finally {
            photoInfoLock.unlock();
        }
    }

    FlickrPhotoInfo getPhotoInfo(FlickrPhoto photo) {
        try {
            photoInfoLock.lock();
            return photoInfo.get(photo.getId());
        } finally {
            photoInfoLock.unlock();
        }
    }

    void storePhotoInfo() {
        photoInfoLock.lock();
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDirectory(), PHOTO_INFO_FILE)))) {
            out.writeObject(photoInfo);
        } catch (Exception ex) {
            MainClass.handleException(null, ex);
        } finally {
            photoInfoLock.unlock();
        }
    }

    void restorePhotoInfo() {
        HashMap<String,FlickrPhotoInfo> newPhotoInfo = new HashMap<>();

        File file = new File(getCacheDirectory(), PHOTO_INFO_FILE);
        if (file.exists()) {
            photoInfoLock.lock();
            try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
                newPhotoInfo = (HashMap<String,FlickrPhotoInfo>)in.readObject();
                photoInfo.clear();
                photoInfo.putAll(newPhotoInfo);
            } catch (IOException | ClassNotFoundException ex) {
                MainClass.handleException(null, ex);
            } finally {
                photoInfoLock.unlock();
            }
        }
    }

    void storePhotoSizes() {
        photoSizesLock.lock();
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDirectory(), PHOTO_SIZES_FILE)))) {
            out.writeObject(photoSizes);
        } catch (Exception ex) {
            MainClass.handleException(null, ex);
        } finally {
            photoSizesLock.unlock();
        }
    }

    void restorePhotoSizes() {
        File file = new File(getCacheDirectory(), PHOTO_SIZES_FILE);
        if (file.exists()) {
            photoSizesLock.lock();
            try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
                HashMap<String,SizeTable> newPhotoSizes = (HashMap<String,SizeTable>)in.readObject();
                photoSizes.clear();
                photoSizes.putAll(newPhotoSizes);
            } catch (IOException | ClassNotFoundException ex) {
                MainClass.handleException(null, ex);
            } finally {
                photoSizesLock.unlock();
            }
        }
    }

    SizeTable getPhotoSizes(FlickrPhoto photo) {
        try {
            photoSizesLock.lock();
            return photoSizes.get(photo.getId());
        } finally {
            photoSizesLock.unlock();
        }
    }

    SizeTable getPhotoSizes(String photoId) {
        try {
            photoSizesLock.lock();
            return photoSizes.get(photoId);
        } finally {
            photoSizesLock.unlock();
        }
    }

    void addPhotoSize(FlickrPhoto photo, SizeTable sizes) {
        photoSizesLock.lock();
        try {
            photoSizes.put(photo.getId(), sizes);
        } finally {
            photoSizesLock.unlock();
        }
    }

    void addPhotoSize(String photoId, SizeTable sizes) {
        photoSizesLock.lock();
        try {
            photoSizes.put(photoId, sizes);
        } finally {
            photoSizesLock.unlock();
        }
    }

    @Override
    public IBlogEntry newBlogEntry() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void openBlogEntryEditor(FlickrBlogEntry entry, File file) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public BlogPostEditorFrame findBlogEntryEditor(FlickrBlogEntry entry) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void publishEntry(FlickrBlogEntry entry) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void onOutboxFrameAction() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void updateEntryAdterRestore(FlickrBlogEntry entry) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ImageIcon getIcon() {
        return Icon.FLICKR.i();
    }

}
